package com.deram.ctin.rest.web.controller.common;

import com.deram.ctin.common.utils.DateUtils;
import com.deram.ctin.dependencies.rest.base.BaseController;
import com.deram.ctin.rest.web.model.common.CommonEnterModel;
import com.deram.ctin.rest.web.model.common.CommonLegalModel;
import com.deram.ctin.rest.web.result.web.WebEdgeResult;
import com.deram.ctin.rest.web.result.web.WebEnterInfoRelationResult;
import com.deram.ctin.rest.web.result.web.WebNodeResult;
import com.deram.ctin.rest.web.result.web.WebTestResult;
import com.deram.ctin.serv.business.api.BusinessInfoApi;
import com.deram.ctin.serv.business.api.BusinessShareholderApi;
import com.deram.ctin.serv.business.entity.BusinessInfo;
import com.deram.ctin.serv.customs.api.CustomsInfoApi;
import com.deram.ctin.serv.customs.api.CustomsTradeApi;
import com.deram.ctin.serv.customs.entity.CustomsInfo;
import com.deram.ctin.serv.customs.entity.CustomsTrade;
import com.deram.ctin.serv.enter.api.EnterInfoApi;
import com.deram.ctin.serv.enter.api.EnterMainUserApi;
import com.deram.ctin.serv.enter.entity.EnterInfo;
import com.deram.ctin.serv.enter.entity.EnterMainUser;
import com.deram.ctin.serv.enter.filter.EnterMainUserFilter;
import com.deram.ctin.serv.search.entity.solr.api.SolrCustomsInfoApi;
import com.deram.ctin.serv.search.entity.solr.api.SolrEnterInfoApi;
import com.deram.ctin.serv.search.entity.solr.bean.SolrCustomsInfo;
import com.deram.ctin.serv.search.entity.solr.bean.SolrEnterInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Api(tags = {"外部测试接口"})
@RestController
@RequestMapping("/common/test")
public class CommonTestController extends BaseController {

    @Autowired
    private EnterInfoApi enterInfoApi;

    @Autowired
    private BusinessInfoApi businessInfoApi;

    @Autowired
    private SolrEnterInfoApi solrEnterInfoApi;

    @Autowired
    private CustomsInfoApi customsInfoApi;

    @Autowired
    private CustomsTradeApi customsTradeApi;

    @Autowired
    private SolrCustomsInfoApi solrCustomsInfoApi;

    @Autowired
    private EnterMainUserApi enterMainUserApi;

    @ApiOperation(value = "后台专用，将数据库中的企业及工商数据导入到搜索引擎")
    @PostMapping("/saveList")
    public void saveList(){
        List<EnterInfo> list = enterInfoApi.findAll();
        solrEnterInfoApi.saveList(list);
    }

//    @GetMapping("/findByKeyWords")
//    public List<SolrEnterInfo> findByKeyWords(String keywords){
//        List<SolrEnterInfo> list = solrEnterInfoApi.searchByKeywords(keywords);
//        return  list;
//    }

    @GetMapping("/findById")
    public SolrEnterInfo findByKeyWords(Long  id){
        SolrEnterInfo info  = solrEnterInfoApi.find(id);
//        solrEnterInfoApi.delete(id);
        return  info;
    }



    @ApiOperation(value = "后台专用，将数据库中的海关数据导入到搜索引擎")
    @PostMapping("/save")
    public void save(){
        List<CustomsTrade> customsInfoList = customsTradeApi.findAll();
        for (int i = 0; i <customsInfoList.size() ; i++) {
            SolrCustomsInfo solrCustomsInfo = solrCustomsInfoApi.save(customsInfoList.get(i));
        }
    }

    @GetMapping("/list")
    public List<SolrCustomsInfo> findByKeyWords(){
        List<SolrCustomsInfo> solrCustomsInfoList = solrCustomsInfoApi.findAll();
//        for (int i = 0; i <solrCustomsInfoList.size() ; i++) {
//            solrCustomsInfoApi.delete();
//        }
        return solrCustomsInfoList;
    }

    @GetMapping("/findEnter")
    public List<SolrEnterInfo> findEnter(){
        List<SolrEnterInfo> solrCustomsInfoList = solrEnterInfoApi.findAll();
//        for (int i = 0; i <solrCustomsInfoList.size() ; i++) {
//            solrCustomsInfoApi.delete();
//        }
        return solrCustomsInfoList;
    }
    @GetMapping("/delete")
    public void delete(Long id){
        solrCustomsInfoApi.delete(id);
    }


    @GetMapping("/test")
    public SolrEnterInfo test(Long enterCode){
        SolrEnterInfo list = solrEnterInfoApi.find(enterCode);
        return list;
    }

    @GetMapping("/String")
    public String[] testString(String enterCode){
        String[] array = enterCode.split("");
        return array;
    }


    @GetMapping("/getEnterInfo")
    public WebTestResult getEnterInfo(Long enterId,Integer roundLevel){
        EnterInfo enterInfo = enterInfoApi.findById(enterId);
        List<EnterInfo> webEnterInfoRelationResultArrayList = Lists.newArrayList();
        List<EnterMainUser> mainUsers =enterMainUserApi.findByEnterInfo(enterInfo.getId());
        List<WebNodeResult> nodelist = Lists.newArrayList();
        List<WebEdgeResult> edgelist = Lists.newArrayList();
        WebNodeResult node = new WebNodeResult();
        node.setId("enter_"+enterId);
        node.setValue(1);
        node.setName(enterInfo.getName());
        nodelist.add(node);
        WebTestResult test = getChild(enterInfo,webEnterInfoRelationResultArrayList,nodelist,edgelist,mainUsers,roundLevel,1,0,new EnterMainUser());
        return test;
    }

//    public  final List<WebEnterInfoRelationResult > getChild(List<EnterInfo> topCategories, Integer  level, List<WebEnterInfoRelationResult> list,Integer roundLevel){
//        level = level + 1 ;
//        WebEnterInfoRelationResult webEnterInfoRelationResult = new WebEnterInfoRelationResult();
//        if(level<=roundLevel) {
//            for (EnterInfo top : topCategories) {
//                webEnterInfoRelationResult.setLevel(level);
//                webEnterInfoRelationResult.setEnterInfo(top);
//                list.add(webEnterInfoRelationResult);
//                getChild(enterInfoApi.searchByFather(top.getId()), level, list, roundLevel);
//            }
//        }
//        return list;
//    }

    public  final  WebTestResult getChild(EnterInfo info,List<EnterInfo> enterList, List<WebNodeResult> nodeList, List<WebEdgeResult> edgeList,List<EnterMainUser> userList,Integer roundLevel,Integer level,Integer type,EnterMainUser user) {
        if (level <= roundLevel) {
            WebTestResult test = new WebTestResult();
            level = level + 1;
            for (EnterInfo enter : enterList) {
                if (type == 0) {
                    WebNodeResult node = new WebNodeResult();
                    WebEdgeResult edge = new WebEdgeResult();
                    node.setId("enter_" + enter.getId());
                    node.setName(enter.getName());
                    node.setValue(1);
                    node.setEnterId(enter.getId());
                    nodeList.add(node);
                    edge.setTarget("enter_" + info.getId());
                    edge.setSourceId(node.getId());
                    edge.setName("参股");
                    edge.setId(UUID.randomUUID().toString());
                    edgeList.add(edge);
                    getChild(enter, enterInfoApi.searchByFather(enter.getId()), nodeList, edgeList, enterMainUserApi.findByEnterInfo(enter.getId()), roundLevel, level, 0, new EnterMainUser());
                } else {
                    WebNodeResult node = new WebNodeResult();
                    WebEdgeResult edge = new WebEdgeResult();
                    node.setId("enter_" + enter.getId());
                    node.setName(enter.getName());
                    node.setValue(1);
                    node.setEnterId(enter.getId());
                    nodeList.add(node);
                    edge.setTarget("user_" + user.getId());
                    edge.setSourceId(node.getId());
                    edge.setName(user.getPosition());
                    edge.setId(UUID.randomUUID().toString());
                    edgeList.add(edge);
                    getChild(enter, enterInfoApi.searchByFather(enter.getId()), nodeList, edgeList, enterMainUserApi.findByEnterInfo(enter.getId()), roundLevel, level, 0, new EnterMainUser());
                }
            }
            for (EnterMainUser mainUser : userList) {
                WebNodeResult node = new WebNodeResult();
                WebEdgeResult edge = new WebEdgeResult();
                node.setId("user_" + mainUser.getId());
                node.setName(mainUser.getName());
                node.setValue(0);
                node.setUserId(mainUser.getId());
                nodeList.add(node);
                edge.setTarget("enter_" + info.getId());
                edge.setSourceId(node.getId());
                edge.setName(user.getPosition());
                edge.setId(UUID.randomUUID().toString());
                edgeList.add(edge);
                EnterMainUserFilter filter = new EnterMainUserFilter();
                getChild(new EnterInfo(), enterMainUserApi.searchByCode(filter), nodeList, edgeList, Lists.newArrayList(), roundLevel, level, 1, mainUser);
            }
            test.setEdgeResults(edgeList);
            test.setWebNodeResultList(nodeList);
            return test;
        }
        return null;
    }

    @GetMapping("/insertEnterInfo")
    public void insertEnterInfo() {
        //单次插入数量
        Long insertNumber = 10000L;
        Long startNumber = 154390L;
        Long stopNUmber = insertNumber + startNumber;
        List<EnterInfo> enterInfoList = Lists.newArrayList();
        List<BusinessInfo> businessInfoList = Lists.newArrayList();
        com.deram.ctin.serv.enter.entity.BaseUpdateInfo<EnterInfo> updateEnterInfo = new com.deram.ctin.serv.enter.entity.BaseUpdateInfo<>();
        com.deram.ctin.serv.business.entity.BaseUpdateInfo<BusinessInfo> updateBusinessInfo = new com.deram.ctin.serv.business.entity.BaseUpdateInfo<>();
        for (Long i = startNumber ; i < stopNUmber; i++) {
            EnterInfo enterInfo = new EnterInfo();
            enterInfo.setEnterCode("00000" + i);
            enterInfo.setLegalReps("法人" + i);
            enterInfo.setLegalRepsCode("10000" + i);
            enterInfo.setName("企业" + i);
            enterInfo.setTelephone("20000" + i);
            enterInfo.setWebsite("系统生成");
            enterInfo.setEmail("企业邮箱" + i);
            enterInfo.setAddress("企业地址" + i);
            enterInfo.setLogoPath("http://mpic.tiankong.com/2a3/3be/2a33be1d492a9f7799610f54dc752f0b/640.jpg");
            enterInfo.setListed(false);
            enterInfo.setUpdateDate(new Date());
            enterInfo.setKeywords(enterInfo.getLegalReps() + ";" + enterInfo.getName() + ";"
                    + enterInfo.getWebsite() + ";" + enterInfo.getEmail() + enterInfo.getAddress() + ";"
                    + enterInfo.getTelephone());

            enterInfoList.add(enterInfo);

            /*EnterInfo insert =  enterInfoApi.save(enterInfo);*/
            Long enterId = i;

            BusinessInfo businessInfo = new BusinessInfo();
            businessInfo.setEnterId(enterId);
            businessInfo.setUnifiedCode("9999" + enterId);
            businessInfo.setTaxpayerIdentity("8999" + enterId);
            businessInfo.setRegistrationNumber("7999" + enterId);
            businessInfo.setOrganizationCode("6999" + enterId);
            businessInfo.setLegalReps(enterInfo.getLegalReps());
            businessInfo.setLegalRepsCode(enterInfo.getLegalRepsCode());
            businessInfo.setRegisteredCapital(new BigDecimal(1000));
            businessInfo.setManagementStatus(1);
            businessInfo.setManagementStatusName("正常");
            businessInfo.setCreationDate(DateUtils.getNow());
            businessInfo.setEnterType(1);
            businessInfo.setEnterTypeName("有限责任公司(自然人投资或控股)");
            businessInfo.setStaffSize("100-2000");
            businessInfo.setOpeningTime(DateUtils.getNow());
            businessInfo.setClosingTime(DateUtils.getNow());
            businessInfo.setRegistrationAuthority("系统生成");
            businessInfo.setApprovalDate(new Date());
            businessInfo.setEnglishName("enter" + enterId);
            businessInfo.setAreaName("中国");
            businessInfo.setIndustryInvolved(enterId % 2 == 1 ? "卫生和社会工作" : "国际组织");
            businessInfo.setUsedName("曾用名" + enterId);
            businessInfo.setBusinessAddress("浙江宁波");
            businessInfo.setBusinessScope("手机技术开发；手机生产、手机服务；（限海淀区永捷北路2号二层经营）从事互联网文化活动；技术开发；货物进出口、技术进出口、代理进出口；销售通讯设备；维修仪器仪表；维修办公设备；承办展览展示活动；会议服务；筹备、策划、组织大型庆典；设计、制作、代理、发布广告。（企业依法自主选择经营项目，开展经营活动；依法须经批准的项目，经相关部门批准后依批准的内容开展经营活动；不得从事本市产业政策禁止和限制类项目的经营活动。）");
            businessInfo.setKeywords(businessInfo.getBusinessAddress() + ";" + businessInfo.getLegalReps() + ";"
                    + businessInfo.getManagementStatusName() + ";" + businessInfo.getEnglishName() + ";"
                    + businessInfo.getAreaName() + ";" + businessInfo.getIndustryInvolved() + ";"
                    + businessInfo.getUnifiedCode()
            );

            businessInfoList.add(businessInfo);

            if (enterInfoList.size() == insertNumber) {
                updateEnterInfo.setList(enterInfoList);
                enterInfoApi.insertList(updateEnterInfo);
                updateBusinessInfo.setList(businessInfoList);
                businessInfoApi.insertList(updateBusinessInfo);

                enterInfoList.clear();
                businessInfoList.clear();
            }
        }
    }
}
